<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "classes".
 *
 * @property integer $id
 * @property string $stu_id
 * @property integer $year
 * @property integer $semester
 * @property string $time
 * @property string $jieshu
 * @property string $course
 * @property string $teacher
 * @property integer $type
 * @property integer $num
 */
class ClassModel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'classes';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['stu_id'], 'required'],
            [['id', 'semester', 'num'], 'integer'],
            [['time'], 'safe'],
            [['name','stu_id', 'teacher', 'year', 'type'], 'string', 'max' => 20],
            [['jieshu', 'course'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '主键ID',
            'stu_id' => '学号',
        	'name' => '姓名',
            'year' => '学年',
            'semester' => '学期',
            'time' => '日期',
            'jieshu' => '节数',
            'course' => '课程名称',
            'teacher' => '任课老师',
            'type' => '类型',
            'num' => '次数或学时数',
        ];
    }


    /**
     * 保存导入excel文件内容
     * @param $data  传入文件内容的数组
     * @return bool  保存成功返回true
     *
     */
    public static function SaveImport($data){

        try{


            foreach ($data as $value){
                $person=new ClassModel();
                $person->stu_id=$value['学号'].'';//学号要转化为字符型才能通过验证
                $person->name=$value['姓名'].'';
                $person->year=$value['学年'].'';
                $person-> semester=(int)$value['学期'];
                $person->time=$value['日期'].'';
                $person->jieshu=$value['节数'].'';
                $person-> course=$value['课程名称'].'';
                $person->teacher=$value['任课老师'].'';
                $person->type=$value['类型'].'';
                //分隔从excel中导入的数据
                if($person->stu_id!=null){//当该行数据有效时
                    $t=explode(':',$value['次数或学时数'],2);
                    $person->num=(int)$t[1];//取后面的数字
                }


                $person->save();
            }
            return true;

        }catch (\Exception $e){
            throw $e;
        }

    }
}
